"use strict";

var wechat = require('wechat'),
    API = wechat.API,
    OAuth = wechat.OAuth,
    crypto = require('crypto'),
    C = require('../common');

var _apiPool = {}, _oauthPool = {},
    WechatApiService = function (appId, appSecret) {

        var key = appId + ':' + appSecret;

        if (key in _apiPool) {
            return _apiPool[key];
        }

        return (_apiPool[key] = new API(appId, appSecret));
    },
    WechatOAuthService = function (appId, appSecret) {

        var key = appId + ':' + appSecret;

        if (key in _oauthPool) {
            return _oauthPool[key];
        }

        return (_oauthPool[key] = new OAuth(appId, appSecret));
    };

WechatOAuthService.sign = function (url, secret) {
    var shasum = crypto.createHash('md5');
    shasum.update(url, 'utf8');
    shasum.update(secret, 'utf8');

    return shasum.digest('base64').substr(0, 8);
};

module.exports = {

    type: 'service',

    load: function (app, config, cb) {
        app.registerService('wechatApi', WechatApiService);
        app.registerService('wechatOAuth', WechatOAuthService);

        cb();
    }
};


